package com.ygo.feihua;

import android.app.*;
import android.os.*;
import android.view.*;
import android.view.View.*;
import com.baidu.location.*;
import com.baidu.mapapi.*;
import com.baidu.mapapi.map.*;
import com.baidu.mapapi.model.*;
import com.baidu.mapapi.radar.*;
import java.io.*;
import android.content.*;
import java.util.*;
import com.baidu.platform.comapi.location.*;
import android.widget.Gallery.*;
import android.graphics.*;
import android.text.*;
import com.baidu.mapapi.search.geocode.*;
import com.ygo.feihua.BmobTable.*;
import cn.bmob.v3.*;
import cn.bmob.v3.listener.*;
import cn.bmob.v3.exception.BmobException;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView;
import android.widget.Toast;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import com.baidu.mapapi.search.core.SearchResult;
import android.widget.Adapter;
import android.util.*;
import com.ygo.feihua.Management.*;
import com.ygo.feihua.util.*;
import com.ygo.feihua.KadianDitu.*;
import com.baidu.mapapi.clusterutil.clustering.*;
import com.ygo.feihua.model.*;
import com.baidu.mapapi.utils.*;
import com.baidu.mapapi.clusterutil.*;
import com.ygo.feihua.utils.*;
import com.ygo.feihua.logo.*;
import com.xiaomi.mistatistic.sdk.*;
import com.ygo.feihua.service.*;

public class KadianDitu extends AppCompatActivity
{

    private MapView mv_cameras;
    private BaiduMap mBaiduMap;
	public LocationClient mLocationClient = null;
	public MyLocationListener myListener ;
	public static List<Activity> activityList = new LinkedList<Activity>();
	double jd=0;
	double wd=0;

	private Button dt_myweizhi,dt_zwduel;
	private DialogUtils du;
	
	public static final String ROUTE_PLAN_NODE = "routePlanNode";
	public static final String SHOW_CUSTOM_ITEM = "showCustomItem";
	public static final String RESET_END_NODE = "resetEndNode";
	public static final String VOID_MODE = "voidMode";
	//导航准备,1为准备好,2为准备中,3为准备失败
	int dhing =2;
	/*
	 *1为选择卡店位置
	 *2为显示某个卡店位置
	 *3为显示所有卡店位置
	 *5为查找周边决斗者
	 */
	int dking=3;
	RadarSearchManager mManager;
	Double jjd,wwd;
	Double fjd=0.0;
	Double fwd=0.0;
	String fcs,fxd;
    //是否跳转到我的位置
    boolean dyx=false;
	Gongju gj;
	int jl;
	private UserManagement um;
	List<RadarNearbyInfo> radar=new ArrayList<RadarNearbyInfo>();
	//private GeoCoder mSearch;
	int xsmode=0;
	MapStatus ms;
	
	boolean mHadRequest = false;

    //城市是否改变
    boolean mIsChangeCity;

    //是否移动
    boolean mIsMove;

    //所有的数量
    int mTotalCount;

    ClusterBaiduItem mPreClickItem;

    Handler mHandler = new Handler();

    //网络请求的线程
 //   NetRunnable mNetRunnable;

    //图标的item
    List<ClusterBaiduItem> mClusterBaiduItems = new ArrayList<>();

    //lbs数据列表
    List<LBSModel> mDataList = new ArrayList<>();

	private SearchModel mSearchModel;

	private MarkerManager mMarkerManager;

	private ClusterManager mClusterManager;

	private Bitmap mCLBitmap;

	private int mMaxPageSize;

	private int mIndex;

	private void surroundingDuelistQuery(){
		
	}
	/**
     * 地图因为操作而发生了状态改变
     */
    private boolean StatusChangeLogic(MapStatus frontMapStatus, MapStatus mapStatus) {
		//显示等级-转换：初始化为mDefaultRadius半径的层级用于显示
        float level = LocationLevelUtils.returnCurZoom(5000);
		
		//初始化数据搜索model
        mSearchModel = new SearchModel();
        mSearchModel.setGps(wd + "," + jd);
        mSearchModel.setRadius(5000);
        mSearchModel.setLevel(level);
        mSearchModel.setTableId(158714);

		
        //重新确定搜索半径的中心图标
        mSearchModel.setGps(mapStatus.bound.getCenter().longitude + "," + mapStatus.bound.getCenter().latitude);
        //重新确定层级
        mSearchModel.setLevel(mapStatus.zoom);

        if (frontMapStatus == null)
            return false;

        //得到屏幕的距离大小
        double areaLength1 = DistanceUtil.getDistance(mapStatus.bound.northeast, mapStatus.bound.southwest);

        //计算屏幕的大小半径
        int radius = (int) areaLength1 / 2;

        //重新确定搜索的半径
        mSearchModel.setRadius(radius);


        if (frontMapStatus.zoom == mapStatus.zoom) {
            if (frontMapStatus.bound == null)
                return false;
            //如果是移动了，得到距离
            double moveLenght = DistanceUtil.getDistance(frontMapStatus.bound.getCenter(), mapStatus.bound.getCenter());
            //如果移动距离大于屏幕的检索半径，请求数据
            if (moveLenght >= radius) {
         //       RequestNewDataLogic(true, true);
                return true;
            }

		
            //如果经纬度发生变化了，一般都是切换的城市之类的
         /*   if (mChangeStatus != null && (mapStatus.target.latitude) != (int) (mChangeStatus.target.latitude)
				&& (int) (mapStatus.target.longitude) != (int) (mChangeStatus.target.longitude) && mIsChangeCity) {
           //     RequestNewDataLogic(true, true);
                mIsChangeCity = false;
                return true;
            }*/

            return false;
        } else {
            //如果是缩放的话，地图层级发生改变，重新请求数据
          //  RequestNewDataLogic(true, true);
            return true;
        }
    }

    /**
     * 请求新数据的逻辑
     */
    /*private void RequestNewDataLogic(final boolean hideFreshBtn, final boolean clearMap) {

        //移动或者缩放之类的产生新的数据请求的时候，需要隐藏掉按键，避免冲突
        if (hideFreshBtn) {
            hideLoading();
        }

        //取消掉原本的请求
        if (mHandler != null && mNetRunnable != null)
            mHandler.removeCallbacks(mNetRunnable);

        //标志位已经移动了
        mIsMove = true;

        mNetRunnable = new NetRunnable(clearMap);
        //等待确定请求逻辑
        mHandler.postDelayed(mNetRunnable, 1300);

    }
*/
    /**
     * 请求数据
     */
    private void netDataLogic(boolean isClearStatus) {
        mHadRequest = true;
        //是否清除掉地图上已经有的
        clearStatus(isClearStatus);
        //请求当前数据是第几页
     //   requestData(mIndex);
    }

    /**
     * 发起真正的请求
     */
  /*  private void requestData(int pageIndex) {
        DemoApplication.getApplication().getJobManager().clear();
        //这个UUID，用于判断当前回来的数据是否为最新请求的数据
        mUUID = UUID.randomUUID().toString();
        //将请求的JOB发布，请求数据，组装数据并返回。
        DemoApplication.getApplication().getJobManager().addJob(new RequestLogicJob(mSearchModel, pageIndex, mUUID));

    }*/

    /**
     * 显示地图ICON marker
     */
    private void showMapData(/*List<LBSModel> dataList,*/ List<ClusterBaiduItem> clusterList/*, int totalCount*/) {
        //总数
       // mTotalCount = totalCount;
        //lbs数据列表
       // mDataList = dataList;
        //组装好的百度item
        mClusterBaiduItems = clusterList;
        //计算有多少页，这里不保险，因为有时候一页不一定是你需要的数量
       /* int page = (int) Math.ceil(((float) totalCount / 50)) - 1;
        //最大页数
        mMaxPageSize = (page >= 0) ? page : 0;

        if (mTotalCount == 0 && (mDataList == null || mDataList.size() == 0)) {
            mIndex = 0;
        }*/
        //清除聚合管理器数据
        mClusterManager.clearItems();
        //重新加入聚合管理器数据
        mClusterManager.addItems(mClusterBaiduItems);

        mBaiduMap.clear();

        //更新状态
        if (mBaiduMap != null && mCurrentMapStatus != null){
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(mCurrentMapStatus));
			Log.e("KadianDitu","不为空刷新");
			}
        //更新页面
        if (mClusterManager != null){
            mClusterManager.cluster();
			Log.e("Kadianditu","刷新界面");
			}

        //下载网络icon
        //DownLoadIcons(mClusterBaiduItems);

        //显示刷新按键
     //   showLoading();

    //    dismissLoadingDialog();

    }

    /**
     * 下载lbs数据中对应的icon作为marker
     */
  /*  private void DownLoadIcons(List<ClusterBaiduItem> clusterBaiduItems) {
        if (clusterBaiduItems == null || clusterBaiduItems.size() == 0)
            return;
        List<IconModel> logoUrl = new ArrayList<>();
        for (int i = 0; i < clusterBaiduItems.size(); i++) {
            ClusterBaiduItem clusterBaiduItem = clusterBaiduItems.get(i);
            //将所有没有下载的market拿出来
            if (!TextUtils.isEmpty(clusterBaiduItem.getMarkerUrl()) && !new File(clusterBaiduItem.getUrlLocalMarkerIconPath()).exists()) {
                IconModel iconModel = new IconModel();
                iconModel.setUrl(clusterBaiduItem.getMarkerUrl());
                iconModel.setId(clusterBaiduItem.getLBAModel().getUid());
                logoUrl.add(iconModel);
            }
        }
        //执行下载图标的job
        if (logoUrl.size() > 0) {
            IConJob iConJob = new IConJob(MainActivity.this, logoUrl);
            DemoApplication.getApplication().getJobManager().addJob(iConJob);
        }
    }
*/

    /**
     * 下载的图标发生了改变
     */
 /*   private void ChangeIconLogic(IconEvent e) {
        for (ClusterBaiduItem clusterBaiduItem : mClusterBaiduItems) {
            LBSModel lbsModel = clusterBaiduItem.getLBAModel();
            //此处根据id设置对应的图片
            if (lbsModel.getUid() == e.geteId()) {
                BitmapDescriptor bitmapDescriptor;
                if (!TextUtils.isEmpty(clusterBaiduItem.getUrlLocalMarkerIconPath()) &&
					new File(clusterBaiduItem.getUrlLocalMarkerIconPath()).exists()) {
                    bitmapDescriptor = clusterBaiduItem.getUrlMarkerIconBitmapDescriptor(false);
                    if (bitmapDescriptor == null) {
                        bitmapDescriptor = clusterBaiduItem.getBitmapDescriptor();
                    }
                } else {
                    bitmapDescriptor = clusterBaiduItem.getBitmapDescriptor();
                }
                //从聚合管理器里面拿到marker，动态改变它
                Marker marker = mClusterManager.getDefaultClusterRenderer().getMarker(clusterBaiduItem);
                if (marker != null) {
                    marker.setIcon(bitmapDescriptor);
                }
                //刷新
                mClusterManager.cluster();
                return;
            }

        }
    }
*/

    /**
     * 点击逻辑
     */
    private void IconClick(ClusterBaiduItem clusterBaiduItem) {
        //恢复上一个点击为正常状态
        if (mPreClickItem != null) {
            mPreClickItem.setBitmapId(R.drawable.dt_qt);
            BitmapDescriptor bitmapDescriptor;
            if (!TextUtils.isEmpty(mPreClickItem.getUrlLocalMarkerIconPath()) &&
				new File(mPreClickItem.getUrlLocalMarkerIconPath()).exists()) {
                bitmapDescriptor = mPreClickItem.getUrlMarkerIconBitmapDescriptor(false);
                if (bitmapDescriptor == null) {
                    bitmapDescriptor = mPreClickItem.getBitmapDescriptor();
                }
            } else {
                bitmapDescriptor = mPreClickItem.getBitmapDescriptor();
            }
            //从聚合管理器里面拿到marker，动态改变它
            Marker marker = mClusterManager.getDefaultClusterRenderer().getMarker(mPreClickItem);
            if (marker != null) {
                marker.setIcon(bitmapDescriptor);
            }
        }
        //设置新的点击为大图状态
        if (clusterBaiduItem != null) {
            clusterBaiduItem.setBitmapId(R.drawable.default_map_icon_big);
            BitmapDescriptor bitmapDescriptor;
            if (!TextUtils.isEmpty(clusterBaiduItem.getUrlLocalMarkerIconPath()) &&
				new File(clusterBaiduItem.getUrlLocalMarkerIconPath()).exists()) {
                bitmapDescriptor = clusterBaiduItem.getUrlMarkerIconBitmapDescriptor(true);
                if (bitmapDescriptor == null) {
                    bitmapDescriptor = clusterBaiduItem.getBitmapDescriptor();
                }
            } else {
                bitmapDescriptor = clusterBaiduItem.getBitmapDescriptor();
            }
            //从聚合管理器里面拿到marker，动态改变它
            final Marker marker = mClusterManager.getDefaultClusterRenderer().getMarker(clusterBaiduItem);
            if (marker != null) {
                marker.setIcon(bitmapDescriptor);
            }
            //刷新
            mClusterManager.cluster();

			ListView ll=(ListView)du. dialogl(false,"请选择你要做的事",new String[]{"信息"});
			ll.setOnItemClickListener(new OnItemClickListener(){

					@Override
					public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
					{
						switch(p3){

							case 0:
								du.dis();
								du.dialogj1(false,"","正在加载,请稍等");
								final LatLng mlatlng1 = marker.getPosition();

								BmobQuery<Kadian> kd=new BmobQuery<Kadian>();
								kd.addWhereEqualTo("kd_wd",mlatlng1.latitude);
								kd.addWhereEqualTo("kd_jd",mlatlng1.longitude);
								kd.order("-updatedAt");
								kd.findObjects( new FindListener<Kadian>(){

										@Override
										public void done(List<Kadian> p1, BmobException p2)
										{
											if(p2==null){
												if(p1.size()!=0){
													du.dis();
													Intent intent1 =new Intent();
													intent1.setClass(KadianDitu.this,KadianXiangxi.class);
													intent1.putExtra("id",p1.get(0).getObjectId());
													startActivity(intent1);			
												}else{
													for(RadarNearbyInfo rr:radar){
														if(rr.pt.equals(mlatlng1)){
															du.dis();
															DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  

															View[] v=du.dialogt1(false,"","用户名:"+rr.comments+"\n最后登录时间:"+df.format(rr.timeStamp));

															Button b1=(Button) v[0];
															b1.setText("确定");
															b1.setOnClickListener(new OnClickListener(){

																	@Override
																	public void onClick(View p1)
																	{
																		du.dis();
																		// TODO: Implemenut this method
																	}
																});
														}

													}


												}


											}else{
												gj.show("查询失败"+p2);
												du.dis();
											}
											// TODO: Implement this method
										}

									});	 
								break;
						}

						// TODO: Implement this method
					}
				});
			
			
        }
        mPreClickItem = clusterBaiduItem;
    }

    /**
     * 聚合点击
     */
    private void ClusterOnClick(Cluster<ClusterBaiduItem> clusterBaiduItems) {
        if (mBaiduMap == null) {
            return;
        }
        if (clusterBaiduItems.getItems().size() > 0) {
            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            for (ClusterBaiduItem clusterBaiduItem : clusterBaiduItems.getItems()) {
                builder.include(clusterBaiduItem.getPosition());
            }
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory
									   .newLatLngBounds(builder.build()));
        }
    }


    /**
     * 清除各种状态
     */
    protected void clearStatus(boolean isClearPageIndex) {
        mBaiduMap.clear();
        mClusterManager.clearItems();
        mClusterBaiduItems.clear();
        if (isClearPageIndex)
            mIndex = 0;
        mIsMove = false;
    }


    /**
     * 请求数据对应的返回
     */
 /*   public void onEventMainThread(RequestDataEvent e) {

        if (e.getEventType() == RequestDataEvent.SUCCESS) {
            //成功，是最新的请求
            if (mUUID.equals(e.getUUID())) {
                showMapData(e.getDataList(), e.getClusterBaiduItems(), e.getTotalSize());
            }
        } else if (e.getEventType() == RequestDataEvent.DEFAULT) {

        } else {
            //没有数据
            if (mUUID.equals(e.getUUID())) {
                if (e.getEventType() == RequestDataEvent.FAIL)
                    Toast.makeText(this, "加载数据失败。", Toast.LENGTH_SHORT).show();
                showLoading();
            }
        }

    }*/
	private MapStatus mCurrentMapStatus;
	
	protected void initListeners() {
		
		//图标管理器
        mMarkerManager = new MarkerManager(mBaiduMap);
        //聚合与渲染管理器
        mClusterManager = new ClusterManager<>(this, mBaiduMap, mMarkerManager);
		mBaiduMap.setOnMapStatusChangeListener(mClusterManager);
		
		//为什么从这里读？这里读出来的size统一
        Bitmap bitmap = CommonUtil.getImageFromAssetsFile(OurygoApplication.getContext(), "current_location.png");

        //调整当前位置图片的显示
        float scale = 0.80f;
        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);
        mCLBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

        bitmap.recycle();

        BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(mCLBitmap);
        MyLocationConfiguration myLocationConfiguration = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, false, bitmapDescriptor);
        mBaiduMap.setMyLocationConfigeration(myLocationConfiguration);
		
		 
        //地图状态发生变化，主要是移动、放大、经纬度发生变化
        mClusterManager.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {

				@Override
				public void onMapStatusChangeStart(MapStatus p1, int p2)
				{
					// TODO: Implement this method
				}


				//记住变化前的上一个状态
				private MapStatus mFrontMapStatus;

				
				@Override
				public void onMapStatusChangeStart(MapStatus mapStatus) {
					if (mFrontMapStatus == null) {
						mFrontMapStatus = mapStatus;
					}
				}

				@Override
				public void onMapStatusChange(MapStatus mapStatus) {
				}

				@Override
				public void onMapStatusChangeFinish(MapStatus mapStatus) {
					//此处需要注意，如果是进入的时候重新定位了地址，或者进入后在改变地图状态，可能也会进入这里
					if (mHadRequest) {
						if (StatusChangeLogic(mFrontMapStatus, mapStatus)) {//处理移动与放大
							mFrontMapStatus = null;
						}
					}
					mCurrentMapStatus = mapStatus;
				}
			});

        //将百度的图标点击转为marker的点击
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
				@Override
				public boolean onMarkerClick(Marker marker) {
					//通过这里转到mClusterManager
					return mMarkerManager.onMarkerClick(marker);
				}
			});

        //单个的点击
        mClusterManager.setOnClusterItemClickListener(new ClusterManager.OnClusterItemClickListener<ClusterBaiduItem>() {
				@Override
				public boolean onClusterItemClick(ClusterBaiduItem item) {
					//Toast.makeText(KadianDitu.this, item.getLBAModel().getTitle(), Toast.LENGTH_SHORT).show();
					IconClick(item);
					return true;
				}
			});

        //聚合的点击
        mClusterManager.setOnClusterClickListener(new ClusterManager.OnClusterClickListener<ClusterBaiduItem>() {
				@Override
				public boolean onClusterClick(Cluster<ClusterBaiduItem> cluster) {
					//Toast.makeText(KadianDitu.this, "聚合图标：" + cluster.getSize(), Toast.LENGTH_SHORT).show();
					ClusterOnClick(cluster);
					return true;
				}
			});

    }
	
	
    @Override
    protected void onCreate(Bundle savedInstanceState)
	{
		
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        // 在使用SDK各组件之前初始化context信息，传入ApplicationContext
        // 注意该方法要再setContentView方法之前实现
		activityList.add(this);
		
        setContentView(R.layout.kadian_ditu);
		
		initView();
		SharedPreferenceUtil.getShareKaiguan().edit().putBoolean("scwz",true).commit();
		startService(new Intent(KadianDitu.this,ServiceMap.class));
		
		gj=Gongju.getdx(this);
		du=DialogUtils.getdx(this);
		um=UserManagement.getDx();
		initListeners();
		
		gj.cshToolbar((Toolbar) findViewById(R.id.toolbar),"卡店地图");	
		
		 Intent intent =this.getIntent();
		 dking=intent.getExtras().getInt("dk");
		 //如果dking为1则是选择卡店位置
		 if(dking==2||dking==4){
			 //显示某个卡店的位置
		 jjd=intent.getExtras().getDouble("jd");
		 wwd=intent.getExtras().getDouble("wd");
		 }else if(dking==5){
			 if(gj.isLogin(this)){
				 View[] vv=du.dialogt(false,"","查询后显示的方式？");
				 Button bb1,bb2;
				 bb1=(Button) vv[0];
				 bb2=(Button) vv[1];
				 bb1.setText("列表显示");
				 bb2.setText("地图显示");

				 bb1.setOnClickListener(new OnClickListener(){

						 @Override
						 public void onClick(View p1)
						 {
							 xsmode=1;
							 du.dis();
							 cxzw();
							 // TODO: Implement this method
						 }
					 });
				 bb2.setOnClickListener(new OnClickListener(){

						 @Override
						 public void onClick(View p1)
						 {
							 xsmode=0;
							 du.dis();
							 cxzw();
							 // TODO: Implement this method
						 }
					 });
			 }
		 }else if(dking==3){
			du.dialogj1(false,"","正在加载卡店,请稍等");
		
			 BmobQuery<Kadian> kd=new BmobQuery<Kadian>();
			 kd.addWhereEqualTo("kdsh",1);
			 kd.order("-updatedAt");
			 kd.findObjects( new FindListener<Kadian>(){

					 @Override
					 public void done(List<Kadian> p1, BmobException p2)
					 {
						 if(p2==null){
							 gj.show("共有"+p1.size()+"个卡店");
							 for(Kadian kdd:p1){
								 fgw(new LatLng(kdd.getKd_wd(),kdd.getKd_jd()));					 
							 }
							 du.dis();
						 }else{
							 gj.show("查询失败"+p2);
							 du.dis();
						 }
						 // TODO: Implement this method
					 }
					 
				 });	 
		 }
		 
      	
		
		//周围决斗者
		dt_zwduel.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View p1)
				{
					
					if(gj.isLogin(KadianDitu.this)){
						View[] vv=du.dialogt(false,"","查询后显示的方式？");
						Button bb1,bb2;
						bb1=(Button) vv[0];
						bb2=(Button) vv[1];
						bb1.setText("列表显示");
						bb2.setText("地图显示");
						
							bb1.setOnClickListener(new OnClickListener(){

									@Override
									public void onClick(View p1)
									{
										xsmode=1;
										du.dis();
										cxzw();
										// TODO: Implement this method
									}
								});
							bb2.setOnClickListener(new OnClickListener(){

									@Override
									public void onClick(View p1)
									{
										xsmode=0;
										du.dis();
										cxzw();
										// TODO: Implement this method
									}
								});
						
						
					
						}
					// TODO: Implement this method
				}
			});
		//我的位置
		dt_myweizhi.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View p1)
				{
                    dyx=true;
					//执行定位前需先停止之前的定位
					mLocationClient.stop();
					initLocation();
					mLocationClient.start();
					// TODO: Implement this method
				}
			});
       
        
        
		//定位图标的点击监听
		mBaiduMap.setOnMyLocationClickListener(new BaiduMap.OnMyLocationClickListener(){

				@Override
				public boolean onMyLocationClick()
				{

					ListView ll=(ListView)du. dialogl(false,"请选择你要做的事",new String[]{"查找周边的决斗者"});
					ll.setOnItemClickListener(new OnItemClickListener(){

							@Override
							public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
							{
								switch(p3){
									case 0:
										
										if(gj.isLogin(KadianDitu.this)){
											View[] vv=du.dialogt(false,"","查询后显示的方式？");
											Button bb1,bb2;
											bb1=(Button) vv[0];
											bb2=(Button) vv[1];
											bb1.setText("列表显示");
											bb2.setText("地图显示");

											bb1.setOnClickListener(new OnClickListener(){

													@Override
													public void onClick(View p1)
													{
														xsmode=1;
														du.dis();
														cxzw();
														// TODO: Implement this method
													}
												});
											bb2.setOnClickListener(new OnClickListener(){

													@Override
													public void onClick(View p1)
													{
														xsmode=0;
														du.dis();
														cxzw();
														// TODO: Implement this method
													}
												});
										}

										break;
								}
								// TODO: Implement this method
							}
						});


					// TODO: Implement this method
					return false;
				}
			});

		//地图覆盖物的单击事件
		mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener(){

				@Override
				public boolean onMarkerClick(final Marker p11)
				{
					
					// TODO: Implement this method
					return mMarkerManager.onMarkerClick(p11);
				}
			});
		//地图的点击事件	
		mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {  
				public void onMapClick(final LatLng point)
				{  
					if (dking == 1)
					{
						ListView ll=(ListView) du.dialogl(false, "请选择你要做的事", new String[]{"添加一个卡店"});
						ll.setOnItemClickListener(new OnItemClickListener(){

								@Override
								public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
								{
									switch (p3)
									{
										case 0:
											mBaiduMap.clear();

											//定义Maker坐标点  
											LatLng point1 = point;
											//构建Marker图标  
											BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.dt_kd);  
											//构建MarkerOption，用于在地图上添加Marker  
											OverlayOptions option = new MarkerOptions().position(point1).icon(bitmap);  
											//在地图上添加Marker，并显示  
											mBaiduMap.addOverlay(option);
											fjd=point.longitude;
											fwd=point.latitude;
											//根据百度坐标查询城市
											GeoCoder gg=GeoCoder.newInstance();
											gg.setOnGetGeoCodeResultListener(new zh());
											gg.reverseGeoCode(new ReverseGeoCodeOption().location(point));
											
											du.dis();
											break;
										
									}


									// TODO: Implement this method
								}

							});		
					}
					//在此处理点击事件  
				}  
				public boolean onMapPoiClick(MapPoi poi)
				{  
					//在此处理底图标注点击事件  
					return false;  
				}  
			});

		myListener = new MyLocationListener();
		mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
		mLocationClient.registerLocationListener(myListener);    //注册监听函数

		if(dking==2||dking==4){
			//定义Maker坐标点  
			LatLng point1 = new LatLng(wwd,jjd);
			//构建Marker图标  
			BitmapDescriptor bitmap1 ;
			if(dking==2){
			bitmap1= BitmapDescriptorFactory.fromResource(R.drawable.dt_kd);  
			}else{
			bitmap1= BitmapDescriptorFactory.fromResource(R.drawable.dt_qt);
			}
			//构建MarkerOption，用于在地图上添加Marker  
			OverlayOptions option = new MarkerOptions().position(point1).icon(bitmap1);  
			//在地图上添加Marker，并显示  
			mBaiduMap.addOverlay(option);

			// 初始化位置
			// 设定中心点坐标 
			LatLng cenpt = new LatLng(wwd,jjd);
			// 定义地图状态(精确到50米)
			MapStatus mMapStatus = new MapStatus.Builder().target(cenpt).zoom(18).build();
			// 定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
			MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
			// 改变地图状态
			mBaiduMap.setMapStatus(mMapStatusUpdate);
		}else{
            dyx=true;
			//如果不是从单个卡店详细信息打开地图即定位自己位置
			initLocation();
			mLocationClient.start();
		}


		mManager = RadarSearchManager.getInstance();
		mManager.addNearbyInfoListener(new cx());
		//设置自动上传的callback和时间间隔,单位毫秒
	//	mManager.startUploadAuto(new zsc(),3000000);	
	
    }

	private void initView()
	{
		
		  // 获取地图控件引用
        mv_cameras = (MapView) findViewById(R.id.mv_cameras);
		//我的位置
		dt_myweizhi = (Button) findViewById(R.id.dt_myweizhi);
		//周围决斗者
		dt_zwduel=(Button) findViewById(R.id.dt_zwduel);
		
		// 类型为普通地图
        mBaiduMap = mv_cameras.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
		//ms = new MapStatus.Builder()/*.target(new LatLng(39.914935, 116.403119))*/.zoom(8).build();
        ms = new MapStatus.Builder().target(new LatLng(wd, jd)).zoom(8).build();
        mBaiduMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback(){

				@Override
				public void onMapLoaded()
				{
					ms = new MapStatus.Builder().zoom(9).build();
					mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(ms));

					// TODO: Implement this method
				}
			});
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(ms));
       
		// TODO: Implement this method
	}
	
	private void cxzw(){
		
		View[] v=du.dialoge(true,"请输入查找范围","单位km,默认1,最大5w公里");
		final EditText e1=(EditText) v[0];
		Button b1=(Button) v[1];
		e1.setInputType(InputType.TYPE_CLASS_NUMBER);
		b1.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View p1)
				{

					String se1=e1.getText().toString().trim();
					if(se1.equals("")){
						se1="1";
					}
					int ie1=Integer.parseInt(se1);
					if(ie1<=50000){
						du.dis();
						du.dialogj1(false,"","正在查找中,请稍等");

						wzsc();

						if(radar.size()!=0){
							radar.clear();
						}
						jl=ie1;

						//构造请求参数，其中centerPt是自己的位置坐标
						RadarNearbySearchOption option2 = new RadarNearbySearchOption().centerPt(new LatLng(wd,jd)).pageNum(0).sortType(RadarNearbySearchSortType.distance_from_near_to_far).radius(ie1*1000).pageCapacity(50);
						//发起查询请求
						mManager.nearbyInfoRequest(option2);
						//        }

					}else{
						gj.show("距离不可大于5w公里");
						du.dis();
					}
				}
				// TODO: Implement this method

			});
		
	}
	
	//定位参数
	private void initLocation()
	{
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Battery_Saving);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
		option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);
    }

    @Override
    protected void onDestroy()
	{
        // 退出时销毁定位
		mLocationClient.stop();
        //停止自动上传位置信息
        mManager.stopUploadAuto();
		//释放地理编码检索实例
	//	mSearch.destroy();
		//移除监听
        mManager.removeNearbyInfoListener(new cx());
        //清除用户信息
    //    mManager.clearUserInfo();
        //释放资源
        mManager.destroy();
        mManager = null;		  
        // 在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mv_cameras.onDestroy();
        super.onDestroy();
	}

    @Override
    protected void onResume()
	{
        super.onResume();
        // 在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mv_cameras.onResume();
		SdkInitManagement.getDx().initMiStats();
		MiStatInterface.recordPageStart(this, "卡店地图");
    }

    @Override
    protected void onPause()
	{
        super.onPause();
        // 在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mv_cameras.onPause();
		MiStatInterface.recordPageEnd();
    }


	

	
	
	
	BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.dt_qt);  
	MarkerOptions mao=new MarkerOptions()
	.icon(bitmap)
	.anchor(0.5f, 0.5f)
	.animateType(MarkerOptions.MarkerAnimateType.grow)
	.perspective(true);
	//构造请求参数，其中centerPt是自己的位置坐标
	RadarNearbySearchOption option2 = new RadarNearbySearchOption().pageCapacity(50).sortType(RadarNearbySearchSortType.distance_from_near_to_far);
	
	public void zcz(int zs, int dqy, int zy)
	{
		if (dqy + 1 < zy)
		{
			option2.centerPt(new LatLng(wd, jd)).pageNum(dqy + 1).radius(jl * 1000);	
			//发起查询请求
			mManager.nearbyInfoRequest(option2);
		}else{
			switch(xsmode){
				case 0:
					//List<MyItem> items = new ArrayList<MyItem>();
					List<ClusterBaiduItem> lc=new ArrayList<ClusterBaiduItem>();
			for (RadarNearbyInfo rr:radar)
			{
				ClusterBaiduItem cl=new ClusterBaiduItem(rr.pt);
				//cl.setUrlClusterPath("/storage/emulated/0/游城废话/我的项目/OURYGO/ourygo/app/src/main/res/drawable-mdpi/back.jpg");
			//	mao.position(rr.pt);
				//cl.setUrlMarkerPath("/storage/emulated/0/游城废话/我的项目/OURYGO/ourygo/app/src/main/res/drawable-mdpi/yh_name.png");
				//在地图上添加Marker，并显示  
			//	mBaiduMap.addOverlay(mao);		
				//items.add(new MyItem(rr.pt));
				lc.add(cl); 
			}
			Log.e("KadianDitu","cl的个数"+lc.size());
			showMapData(lc);
					//mClusterManager.addItems(items);
					
			
			du.dis();
			break;
			case 1:
					
				du.dis();
				View[] v=du.dialogjdz(true,zs+"个决斗者",radar);
				ListView li=(ListView) v[0];
				Button bb=(Button) v[1];
				
				
					li.setOnItemClickListener(new OnItemClickListener(){

							@Override
							public void onItemClick(AdapterView<?> p1, View p2, final int p33, long p4)
							{
								ListView lv=(ListView) du.dialogl(true,radar.get(p33).comments,new String[]{"查看用户信息","显示用户坐标"});
								lv.setOnItemClickListener(new OnItemClickListener(){

										@Override
										public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
										{
											switch(p3){
											case 0:
													du.dis();
													if(radar.get(p33).comments.equals("未登录")||radar.get(p33).comments.equals("用户备注信息")){
														
														gj.show("用户未登录");
													}else{
														Intent intent=new Intent(KadianDitu.this,YonghuMingpian.class);
														intent.putExtra("name",radar.get(p33).comments);
														startActivity(intent);
														
														
													}
													break;
												case 1:
													du.dis();
													du.dis();
													mao.position(radar.get(p33).pt);
													//在地图上添加Marker，并显示  
													mBaiduMap.addOverlay(mao);		
													
													LatLng cenpt = radar.get(p33).pt;
													// 定义地图状态(精确到50米)
													MapStatus mMapStatus = new MapStatus.Builder().target(cenpt).zoom(18).build();
													// 定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
													MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
													// 改变地图状态
													mBaiduMap.setMapStatus(mMapStatusUpdate);
													break;
											}
											
											// TODO: Implement this method
										}
									});
								
								
								// TODO: Implement this method
							}
						});
				bb.setText("确定");
					bb.setOnClickListener(new OnClickListener(){

							@Override
							public void onClick(View p1)
							{
								du.dis();
								// TODO: Implement this method
							}
						});
				break;
			}
			gj.show("查询周边成功,周边共有" + zs + "个决斗者");

		}
	}


	//查询周边决斗者监听
	public class cx implements RadarSearchListener
	{
		@Override
		public void onGetUploadState(RadarSearchError p1)
		{
			//上传监听
			// TODO: Implement this method
		}

		@Override
		public void onGetClearInfoState(RadarSearchError p1)
		{
			// TODO: Implement this method
		}


		@Override
		public void onGetNearbyInfoList(RadarNearbyResult result,RadarSearchError error) {
			// TODO Auto-generated method stub

			if (error == RadarSearchError.RADAR_NO_ERROR)
			{
				for (RadarNearbyInfo rr:result.infoList)
				{
					radar.add(rr);
				}	
				zcz(result.totalNum, result.pageIndex, result.pageNum);

				
			}else{
				//获取失败
				if (error == RadarSearchError.RADAR_NO_RESULT)
				{
					gj.show("周边无决斗者");
					du.dis();
					mBaiduMap.clear();
				}else{
					du.dis();
					gj.show("查询周边失败" + error);
				}

			}
		}	
	}
	
	
	//周边雷达信息位置上传
	public void wzsc(){
        
        String yid = "未登录";
        if(um.getUser()!=null){
            yid=um.getUser().getUsername();
        }
        //周边雷达设置用户身份标识，id为空默认是设备标识
        mManager.setUserID(null);
        //上传位置
        RadarUploadInfo info = new RadarUploadInfo();
        LatLng pt = new LatLng(wd,jd);
        info.comments = yid;
        info.pt = pt;
        mManager.uploadInfoRequest(info);

	}

	//转换结果
	public class zh implements OnGetGeoCoderResultListener
	{
		//地理编码查询
		@Override
		public void onGetGeoCodeResult(GeoCodeResult p1)
		{
			Log.e("Kadianditu","地理编码转换");
			// TODO: Implement this method
		}
		//地理编码反查询
		@Override
		public void onGetReverseGeoCodeResult(ReverseGeoCodeResult p1)
		{
			Log.e("Kadianditu","反地理编码转换");
			//详细地址
			fxd=p1.getAddress();
			//城市,由于获得的城市带有“市”,所以需要去掉最后一个字符串
			fcs=p1.getAddressDetail().city;
			fcs=fcs.substring(0,fcs.length()-1);
			Intent intent=new Intent();
			intent.putExtra("jd",fjd);
			intent.putExtra("wd",fwd);
			intent.putExtra("cs",fcs);
			intent.putExtra("xd",fxd);
			setResult(0,intent);
			finish();
			// TODO: Implement this method
		}
}

/*

	//自动上传用户位置信息,用于查找周边决斗者定位
	public class zsc implements RadarUploadInfoCallback
	{
		//实现上传callback，自动上传
		@Override
		public RadarUploadInfo onUploadInfoCallback()
		{	
        dyx=false;
            //执行定位前需先停止之前的定位
            mLocationClient.stop();
            initLocation();
            mLocationClient.start();
        MyUser yh=BmobUser.getCurrentUser(MyUser.class);
        String yid = "未登录"; 
        if(yh!=null){
            yid=yh.getUsername();
        }
            mManager.setUserID(null);
        
			RadarUploadInfo info = new RadarUploadInfo();
			info.comments = yid;
			info.pt = new LatLng(wd,jd);
            
			return info;
		}
	}
*/
	//定位回调方法
	public class MyLocationListener implements BDLocationListener
	{

		@Override
		public void onReceiveLocation(BDLocation location)
		{	
			jd= location.getLongitude();
			wd= location.getLatitude();
			if (wd == 0 | jd == 0)
			{
				gj.show("定位失败,原因为" + location.getLocType());
				return;
			}

			// 开启定位图层  
			mBaiduMap.setMyLocationEnabled(true);  
// 构造定位数据  
			MyLocationData locData = new MyLocationData.Builder()  
				.accuracy(location.getRadius())  
				// 此处设置开发者获取到的方向信息，顺时针0-360  
				.direction(100).latitude(location.getLatitude())  
				.longitude(location.getLongitude()).build();  
// 设置定位数据  
			mBaiduMap.setMyLocationData(locData);  
// 设置定位图层的配置（定位模式，是否允许方向信息，用户自定义定位图标）  
		/*	BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory  
				.fromResource(R.drawable.dt_qita);  */
			MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, null);  
			mBaiduMap.setMyLocationConfigeration(config);  

			if(dyx){
			// 初始化位置
			// 设定中心点坐标 
			LatLng cenpt = new LatLng(wd,jd);
			// 定义地图状态(精确到50米)
			MapStatus mMapStatus = new MapStatus.Builder().target(cenpt).zoom(18).build();
			// 定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
			MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
			// 改变地图状态
			mBaiduMap.setMapStatus(mMapStatusUpdate);
            }
            dyx=true;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		// TODO: Implement this method
		if(keyCode==KeyEvent.KEYCODE_BACK){
			Intent intent=new Intent();
			intent.putExtra("jd",0.0);
			intent.putExtra("wd",0.0);
			intent.putExtra("cs","");
			intent.putExtra("xd","");
			setResult(0,intent);
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}
	BitmapDescriptor bitmap1 = BitmapDescriptorFactory.fromResource(R.drawable.dt_kd);  
	
public void fgw(LatLng la){
	//定义Maker坐标点  
	LatLng point1 = la;
	//构建Marker图标  
		//构建MarkerOption，用于在地图上添加Marker  
	OverlayOptions option = new MarkerOptions().position(point1).icon(bitmap1);  
	//在地图上添加Marker，并显示  
	mBaiduMap.addOverlay(option);
	
	
}/*
	OnGetGeoCoderResultListener listener = new OnGetGeoCoderResultListener() {  
		public void onGetGeoCodeResult(GeoCodeResult result) {  
			if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {  
				//没有检索到结果  
				gj.show("未找到该地址");
				du.dis();
				
			}  else{
				du.dis();
				gj.show(result.getAddress());
				MapStatus mMapStatus = new MapStatus.Builder().target(result.getLocation()).zoom(18).build();
				// 定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
				MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
				// 改变地图状态
				mBaiduMap.setMapStatus(mMapStatusUpdate);
				
			}
			
			
			//获取地理编码结果  
		}  

		@Override  
		public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {  
			if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {  
				//没有找到检索结果  
			}  
			//获取反向地理编码结果  
		}  
	};
*/
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// TODO: Implement this method
		//	menu.add(1,1,1,"设置");


		getMenuInflater().inflate(R.menu.menu_kd, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		// TODO: Implement this method
		switch(item.getItemId()){
			/*case R.id.kd_ss:
				View[] v=du.dialoge(false,"","搜索地区");
				final EditText ed=(EditText) v[0];
				Button b=(Button) v[1];
				b.setOnClickListener(new OnClickListener(){

						@Override
						public void onClick(View p1)
						{
							String e=ed.getText().toString().trim();
							
							du.dis();
							du.dialogj1(false,"","查询中,请稍等");
							mSearch.geocode(new GeoCodeOption()  
								.city("南充")
											.address(e));
							// TODO: Implement this method
						}
					});
				
				
				break;*/
			case R.id.kd_rz:
				startActivity(new Intent(this,KadianRenzheng.class));
				break;		
			case R.id.kd_myrz:
				startActivity(new Intent(this,KadianShenhe.class));
			break;
		}
		return super.onOptionsItemSelected(item);
	}



}


